<?php

class RightMenu
{
    public static function Generate( $pageId )
    {
        $tmpl = Core::CreateTemplateEngine( PATH_TEMPLATES."include/menu/right/" );

        $tmpl->define("active",           "active.tpl");
        $tmpl->define("selected",         "selected.tpl");
        $tmpl->define("submenu",          "submenu.tpl");
        $tmpl->define("submenu_no_link",  "submenu_no_link.tpl");
        $tmpl->define("submenu_selected", "submenu_selected.tpl");

        $menu = '';
        $rootPage = Pages::GetRootPage();
        foreach ( $rootPage->children as $id )
        {
            $pageInfo = Pages::GetPageInfo($id);
            if ( $pageInfo->right )
            {
                $menu .= self::GenerateRecursive($pageInfo, $tmpl, $pageId);
            }
        }

        return $menu;
    }

    private static function GenerateRecursive( PageInfo $pageInfo, TemplateEngine $tmpl, $selectedPageId, &$containsSelectedPage = false )
    {
        $tmpl->set('menu', '');
        if ( $pageInfo->right )
        {
            $containsSelectedPage = $selected = ($pageInfo->id == $selectedPageId);

            $childCount = 0;
            foreach ( $pageInfo->children as $id )
            {
                $child = Pages::GetPageInfo($id);
                if ($child->right)
                {
                    $childCount++;
                }
            }

            if ( $childCount > 0 )
            {
                $submenuContent = '';
                foreach ( $pageInfo->children as $id )
                {
                    $child = Pages::GetPageInfo($id);
                    $submenuContent .= self::GenerateRecursive($child, $tmpl, $selectedPageId, $childSelected);
                    $containsSelectedPage |= $childSelected; 
                }

                $tmpl->clearVars();
                $tmpl->set('TEXT', $pageInfo->name);
                $tmpl->set('SUBMENU', $submenuContent);
                $tmpl->set('ID_ITEM', $pageInfo->id);
                $tmpl->set('CONTAINS_SELECTED_ITEM', Util::GetBooleanAsString($containsSelectedPage));

                if ( $pageInfo->link )
                {
                    $tmpl->set('LINK', UrlHelper::GetAbsolutePath($pageInfo->path));
                    $tmpl->parse("menu", $selected ? "submenu_selected" : "submenu");
                }
                else
                {
                    $tmpl->parse("menu", "submenu_no_link");
                }
            }
            else
            {
                $tmpl->set('LINK', UrlHelper::GetAbsolutePath($pageInfo->path));
                $tmpl->set('TEXT', $pageInfo->name);
                $tmpl->parse("menu", $selected ? "selected" : "active");
            }
        }

        return $tmpl->getGenerated('menu');
    }
}

?>
